//
//  FGVisitorMessagesViewController.m
//  AFNetworking
//
//  Created by feige on 2023/5/8.
//

#import "FGVisitorMessagesViewController.h"
#import <FGChatUI/UIColor+FGKeyboard.h>
#import <FGChatUI/FGResources.h>
#import <FGChatKit/FGChatKit.h>
#import "FGMessageConvert.h"
#import <HLTool/HLUtils.h>
#import <FGChatUI/FGKeyboard.h>
#import <HLTool/HLToastTool.h>
#import <FGChatUI/NSDate+FGTime.h>
#import <HLTool/HLPhotoTool.h>
#import <FGChatUI/FGMessageWebViewController.h>

@interface FGVisitorMessagesViewController ()<FGChatKitDelegate, UIDocumentPickerDelegate, FGMessagesViewControllerDelegate>

@end

@implementation FGVisitorMessagesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.senderId = [FGChatKit sharedKit].chatSelfId;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.delegate = self;
    
    [self setupKeyboard];
    [self setupMoreItem];
    
    [[FGChatKit sharedKit] addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    // 回执房间所有消息
    [self receiptAllMessage];
}

- (void)dealloc {
    [[FGChatKit sharedKit] removeDelegate:self];
}

#pragma mark - Private Method

- (void)setupKeyboard
{
    FGKeyboardConfiguration *kbConfiguration = [[FGKeyboardConfiguration alloc] init];
    kbConfiguration.lineColor = [UIColor kb_colorWithString:@"#EBF1F5"];
    kbConfiguration.bgColor = [UIColor whiteColor];
    kbConfiguration.inputColor = [UIColor kb_colorWithString:@"#F0F2F5"];
    kbConfiguration.borderColor = [UIColor kb_colorWithString:@"#F0F2F5"];
    kbConfiguration.cornerRadius = 20;
    self.keyboardView.showVoice = NO;
    self.keyboardView.showInside = NO;
    self.keyboardView.configuration = kbConfiguration;
}

- (void)setupMoreItem
{
    NSArray *imageNames = @[@"chat_more_icons_camera", @"chat_more_icons_file"];
    NSArray *titles = @[@"图片", @"文件"];
    
    NSMutableArray *array = [NSMutableArray new];
    [imageNames enumerateObjectsUsingBlock:^(NSString *imageName, NSUInteger idx, BOOL * _Nonnull stop) {
        FGKeyboardMoreItem *item = [FGKeyboardMoreItem moreItemWithType:idx + 1 title:titles[idx] image:[FGResources getImageFromMessage:imageName]];
        [array addObject:item];
    }];
    
    [self setMoreItem:array];
}

/// 回执房间所有消息
- (void)receiptAllMessage
{
    [[FGChatKit sharedKit] roomMessageReceipt:self.conversationId callBlock:^(NSInteger code, NSString *msg, id data) {}];
}

/// 撤回消息
- (void)revokeMessage:(FGMessageCellData *)msg
{
    // 判断是否超过撤回时间
    NSInteger interval = [[NSDate timestamp:[NSDate date]] longLongValue] - [msg.time longLongValue];
    if (interval > 60 * 1 * 1000) {
        [HLToastTool show:@"该消息已超过1分钟，不能撤回"];
        return;
    }
}

/**
 * 处理url带中文问题
 */
+ (NSString *)fg_UTF8EncodeURL:(NSString *)urlString
{
    if (urlString && urlString.length > 0)
    {
        NSString *encodedString = (NSString *)
        CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                  (CFStringRef)urlString,
                                                                  (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
                                                                  NULL,
                                                                  kCFStringEncodingUTF8));
        return encodedString;
    }
    else
    {
        return @"";
    }
}

/// 上传图片消息中的图片
- (void)uploadImage:(FGChatMessageModel *)model data:(FGImageMessageCellData *)data
{
    [[FGChatKit sharedKit] uploadImage:[data getOriginImage] success:^(BOOL succeed, NSString *cmsg, NSString *url) {
        if (succeed) {
            [self uploadSucc:model data:data url:url];
        } else {
            [self uploadFail:model data:data];
        }
    } failure:^{
        [self uploadFail:model data:data];
    }];
}

/// 上传文件消息中的文件
- (void)uploadFile:(FGChatMessageModel *)model data:(FGFileMessageCellData *)data
{
    NSData *fileData = [NSData dataWithContentsOfFile:data.path];
    
    [[FGChatKit sharedKit] uploadFlieData:fileData fileName:data.fileName success:^(BOOL succeed, NSString *msg, NSString *url) {
        if (succeed) {
            [self uploadSucc:model data:data url:url];
        } else {
            [self uploadFail:model data:data];
        }
    } failure:^{
        [self uploadFail:model data:data];
    }];
     
}

/// 上传成功
- (void)uploadSucc:(FGChatMessageModel *)model data:(FGMessageCellData *)data url:(NSString *)url
{
    model.content = url;
    model.sendStatus = FGChatMessageSendStatusSending;
    
    // send to serve
    [[FGChatKit sharedKit] sendMessage:model callBlock:^(NSInteger code, NSString *msg, id data) {}];
    
    // ui
    data.status = FGMsgStatusSending;
    if ([data isKindOfClass:FGImageMessageCellData.class]) {
        for (FGImageItem *item in ((FGImageMessageCellData *)data).items) {
            item.url = url;
        }
    } else if ([data isKindOfClass:FGFileMessageCellData.class]) {
        ((FGFileMessageCellData *)data).url = url;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

/// 上传失败
- (void)uploadFail:(FGChatMessageModel *)model data:(FGMessageCellData *)data
{
    // ui
    data.status = FGMsgStatusFail;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

#pragma mark - Rewrite Mehtod

/// 加载历史记录
- (void)loadMessage:(FGMessageCellData *)msg complation:(void (^)(BOOL, NSArray * _Nonnull))complation {
    
    NSString *beginTime = [HLUtils stringFromFomate:[NSDate date] formate:@"yyyy-MM-dd HH:mm:ss"];
    if (self.dataArray.count > 0) {
        FGMessageCellData *cellData = self.dataArray.firstObject;
        beginTime = [HLUtils dateStringWithTimestamp:@(cellData.time.longLongValue) formate:@"yyyy-MM-dd HH:mm:ss"];
    }
    [[FGChatKit sharedKit] getOfflineMessage:[self.conversationId componentsSeparatedByString:@"@"].firstObject
                                   beginTime:beginTime
                                        type:1
                                   callBlock:^(NSInteger code, NSString *msg, id data) {
        if (code == 200) {
            NSArray<FGChatMessageModel *> *models = (NSArray<FGChatMessageModel *> *)data;
            NSMutableArray *cellDatas = [NSMutableArray new];
            if (models.count > 0) {
                for (FGChatMessageModel *model in models) {
                    FGMessageCellData *cellData = [FGMessageConvert cellDataForMessage:model];
                    [self showMessageTimeWithData:cellData];
                    [cellDatas addObject:cellData];
                }
            }
            
            complation(YES, cellDatas);
        } else {
            complation(YES, @[]);
        }
    }];
}


/// 发送前处理
- (void)sendMessage:(FGMessageCellData *)msg complation:(void (^)(BOOL, FGMessageCellData * _Nonnull))complation {
    FGChatMessageModel *model = [FGMessageConvert messageForCellData:msg room:self.conversationId websiteId:[FGChatKit sharedKit].websiteId];
    // 文字
    if ([msg isKindOfClass:FGTextMessageCellData.class]) {
        ((FGTextMessageCellData *)msg).textColor = [UIColor whiteColor];
        [[FGChatKit sharedKit] sendMessage:model callBlock:^(NSInteger code, NSString *msg, id data) {}];
    }
    // 图片
    else if ([msg isKindOfClass:FGImageMessageCellData.class]) {
        FGImageMessageCellData *tempData = (FGImageMessageCellData *)msg;
        [self uploadImage:model data:tempData];
    }
    // 文件
    else if ([msg isKindOfClass:FGFileMessageCellData.class]) {
        FGFileMessageCellData *tempData = (FGFileMessageCellData *)msg;
        [self uploadFile:model data:tempData];
    }
    // 模板
    else if ([msg isKindOfClass:FGTemplateMessageCellData.class]) {
        [[FGChatKit sharedKit] sendMessage:model callBlock:^(NSInteger code, NSString *msg, id data) {}];
    }
    
    // msg
    msg.msgId = model.mid;
    msg.sender = self.senderId;
    
    // 处理时间显示
    [self showMessageTimeWithData:msg];
    
    if (complation) {
        complation(YES, msg);
    }
}

#pragma mark - FGChatKitDelegate

/**
 * 收到消息
 */
- (void)chatKitDidReceiveMessage:(FGChatMessageModel *)message
{
    // 回执非自己发送的消息
    if (!message.isSelfSend) {
        [[FGChatKit sharedKit] messageReceipt:message.mid
                                         from:message.from
                                    callBlock:^(NSInteger code, NSString *msg, id data) {}];
    }
    
    FGMessageCellData *cellData = [FGMessageConvert cellDataForMessage:message];
    FGMessageCellData *haveCellData = [self dataOfUUID:cellData.msgId];
    // 更新
    if (haveCellData) {
        [self changeMsg:haveCellData status:cellData.status];
    }
    // 新增
    else {
        // 处理时间显示
        [self showMessageTimeWithData:cellData];
        [self acceptMessages:@[cellData]];
        [self scrollToBottom:YES];
    }
}

/**
 * 收到结束会话
 */
- (void)chatKitDidReceiveEndSession
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 * 收到消息已读回执
 */
- (void)chatKitDidReceiveReadReceipt:(NSString *)mid
{
    FGMessageCellData *haveCellData = [self dataOfUUID:mid];
    // 更新
    if (haveCellData) {
        haveCellData.isread = @"已读";
        [self changeMsg:haveCellData status:haveCellData.status];
    }
}

/**
 * 收到撤回消息
 */
- (void)chatKitDidReceiveRevokeMessage:(NSString *)mid
{
    FGMessageCellData *haveCellData = [self dataOfUUID:mid];
    if (haveCellData) {
        NSString *text = [NSString stringWithFormat:@"“%@”撤回了一条消息", haveCellData.name];
        [self onRevoke:text msgId:mid];
    }
}

#pragma mark - UIDocumentPickerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
    
    NSURL *url = urls.firstObject;
    
    if ([url startAccessingSecurityScopedResource]) {
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            
            if (fileData.length > 5 * 1024 * 1024) {
                [HLToastTool show:@"文件不能大于5M"];
                return;
            }
            
            // 发送文件消息
            FGFileMessageCellData *data = [[FGFileMessageCellData alloc] initWithDirection:FGMsgDirectionOutgoing];
            data.conversationId = self.conversationId;
            data.fileName = fileName;
            data.length = (int)fileData.length;
            NSString *path = [data getFilePath];
            [fileData writeToFile:path atomically:YES];
            data.path = path;
            [self sendMessage:data];
            
        }];
        [url stopAccessingSecurityScopedResource];
    }
    
}

#pragma mark - FGMessagesViewControllerDelegate

/// 点击更多中的item
- (void)messageController:(FGMessagesViewController *)controller onSelectMoreItem:(FGKeyboardMoreItem *)item {
    switch (item.type) {
        case 1:
        {
            [HLPhotoTool sheetImagePickerWithController:self
                                                  title:@"照片"
                                                  count:1
                                                   edit:NO
                                             completion:^(NSArray<HLPhotoModel *> * _Nonnull images) {
                [self sendMessageImage:images.firstObject.image];
            }];
            
        }
            break;
        case 2:
        {
            NSArray *documentTypes = @[@"public.content",@"public.data", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
            UIDocumentPickerViewController *vc = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
            vc.delegate = self;
            [self presentViewController:vc animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
    
}

/// 点击头像
- (void)messageController:(FGMessagesViewController *)controller onSelectMessageAvatar:(FGMessageCell *)cell {
    
}

/// 点击消息
- (void)messageController:(FGMessagesViewController *)controller onSelectMessageContent:(FGMessageCell *)cell {
    // 图片
    if ([cell isKindOfClass:[FGImageMessageCell class]]) {
        FGImageMessageCell *imageMessageCell = (FGImageMessageCell *)cell;
        [HLPhotoTool showImageWithController:self
                                      source:@[[imageMessageCell.imageData getPreviewImage]]
                                    previews:@[imageMessageCell.thumbView]
                                       index:0];
    }
    // 文件
    else if ([cell isKindOfClass:[FGFileMessageCell class]]) {
        FGFileMessageCell *fileMessageCell = (FGFileMessageCell *)cell;
        FGMessageWebViewController *vc = [[FGMessageWebViewController alloc] init];
        vc.title = fileMessageCell.fileData.fileName;
        vc.url = [FGVisitorMessagesViewController fg_UTF8EncodeURL:fileMessageCell.fileData.url];
        [self.navigationController pushViewController:vc animated:YES];
    }
    // 模板
    if ([cell isKindOfClass:[FGTemplateMessageCell class]]) {
        NSDictionary *data = ((FGTemplateMessageCell *)cell).templateData.templateData;
        NSInteger type = [data[@"type"] integerValue];
        NSString *url = [data valueForKeyPath:@"data.linkUrl"];
        if ((type != 3 && type != 4) || !url) {
            return;
        }
        FGMessageWebViewController *vc = [FGMessageWebViewController new];
        vc.url = url;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

/// 长按消息是否弹出menu
- (BOOL)messageController:(FGMessagesViewController *)controller willShowMenuInCell:(FGMessageCell *)view {
    return YES;
}

/// 长按消息弹出menu的选项
- (NSArray<NSString *> *)messageController:(FGMessagesViewController *)controller menuItemIncell:(FGMessageCell *)cell {
    NSMutableArray *arr = [NSMutableArray array];
    
    // 撤回 自己的消息1分钟
    NSInteger interval = [[NSDate timestamp:[NSDate date]] longLongValue] - [cell.messageData.time longLongValue];
    if (cell.messageData.direction == FGMsgDirectionOutgoing && cell.messageData.status == FGMsgStatusSucc) {
        // 毫秒
        if (interval < 60 * 1 * 1000) {
            [arr addObject:@"撤回"];
        }
    }
    
    return arr;
}

/// 点击munu的选项
- (void)messageController:(FGMessagesViewController *)controller onSelectMenu:(NSString *)title msg:(FGMessageCellData *)msg {
    if ([title isEqualToString:@"撤回"]) {
        [self revokeMessage:msg];
    }
}

/// 点击FGNoticeView Title
- (void)messageController:(FGMessagesViewController *)controller noticeView:(FGNoticeView *)noticeView clickTitle:(NSString *)title {

}

/// 图片消息，图片下载完成
- (void)messageController:(FGMessagesViewController *)controller imageDownloadComplete:(FGMessageCell *)cell {

}

/// 表单提交
- (void)messageController:(FGMessagesViewController *)controller submitFrom:(NSArray *)fromArr
{
    BOOL isOK = YES;
    NSMutableDictionary *fromDict = [NSMutableDictionary new];
    for (NSDictionary *dict in fromArr) {
        NSString *value = dict[@"value"];
        if ([dict[@"isRequired"] boolValue] && value.length == 0) {
            isOK = NO;
            [HLToastTool show:[NSString stringWithFormat:@"%@不能为空", dict[@"fieldName"]]];
            break;
        }
        fromDict[dict[@"labelName"]] = value;
    }
    
    if (!isOK) {
        return;
    }
    
    [[FGChatKit sharedKit] submitFrom:fromDict callBlock:^(NSInteger code, NSString *msg, id data) {
        if (code == 200) {
            [HLToastTool show:@"提交成功"];
        } else {
            [HLToastTool show:msg];
        }
    }];
}

/**
 templateDict格式：
 {
     "operationType":1,
     "content":"",
     "id":113,
     "isRecommend":true,
     "title":"账号无法登录",
     "updateTime":"2022-10-26 09:22:22",
     "tagId":128,
     "createTime":"2022-10-26 09:22:22",
     "url":"https:\/\/www.cnblogs.com\/zhaoxiaobei\/p\/9283875.html"
 }
 */
/// 表点击了模板消息上的Cell
- (void)messageController:(FGMessagesViewController *)controller didSelectedTemplateMessageCell:(NSDictionary *)templateDict
{
    NSInteger operationType = [templateDict[@"operationType"] integerValue];
    // 链接
    if (operationType == 1) {
        NSString *url = templateDict[@"url"];
        if (!url) {
            return;
        }
        FGMessageWebViewController *vc = [FGMessageWebViewController new];
        vc.url = url;
        [self.navigationController pushViewController:vc animated:YES];
    }
    // 发送自动消息
    else if (operationType == 2) {
        NSString *content = templateDict[@"content"];
        [[FGChatKit sharedKit] sendSystemMessage:content room:self.conversationId callBlock:^(NSInteger code, NSString *msg, id data) {}];
    }
}

@end
